package com.cn.xiaonuo.slbfinances.shopassets.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.ExportExcelUtils;
import com.cn.xiaonuo.common.utils.pageutil.PageUtil;
import com.cn.xiaonuo.common.vo.ExcelData;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlMerchantAssets;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlShopWallet;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlbShop;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlMerchantAssetsMapper;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopMapper;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopWalletLogMapper;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopWalletMapper;
import com.cn.xiaonuo.slbfinances.shopassets.param.PageMerchantAssetsParam;
import com.cn.xiaonuo.slbfinances.shopassets.rsp.PageMerchantAssetsRsp;
import com.cn.xiaonuo.slbfinances.shopassets.service.SlMerchantAssetsService;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlOrderDetail;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlShopPayment;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlOrderMapper;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlShopPaymentMapper;
import com.cn.xiaonuo.slbfinances.slbshopes.mapper.SlbShopMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @BelongsProject: slb-reports-java
 * @Author: likui
 * @CreateTime: 2022-12-20  15:03
 * @Description: TODO
 */
@Slf4j
@Service
public class SlMerchantAssetsServiceImpl implements SlMerchantAssetsService {

    @Autowired
    private SlShopMapper slShopMapper;
    @Autowired
    private SlMerchantAssetsMapper slMerchantAssetsMapper;
    @Autowired
    private SlOrderMapper slOrderMapper;
    @Autowired
    private SlShopWalletMapper slShopWalletMapper;

    @Autowired
    private SlShopPaymentMapper slShopPaymentMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage summarizeAssets() {
        BusinessMessage message = new BusinessMessage();
        log.info("搜了宝商家资产汇总定时任务执行开始!");
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        String createTime = fmt.format(calendar.getTime());
        Integer count=0;
        try {
            //查询已结算涉及店铺
            List<Map<String, Object>> getSettlementShop = slOrderMapper.getSettlementShop(createTime);
            for (Map shopId : getSettlementShop) {
                SlbShop slbShop = slShopMapper.selectById(Convert.toInt(shopId.get("shopId")));
                if (ObjectUtils.isEmpty(slbShop)) {
                    log.info("该店铺信息异常，ID为{}", Convert.toInt(shopId.get("shopId")));
                    break;
                }
                SlMerchantAssets assets = new SlMerchantAssets();
                assets.setShopId(slbShop.getId());
                assets.setShopName(slbShop.getName());
                assets.setSlShopType(slbShop.getSlShopType());
                assets.setUserId(slbShop.getOwnerId());
                assets.setType(2);
                //当日合计收入
                SlMerchantAssets totalIncome = slOrderMapper.totalIncome(slbShop.getId(), createTime);
                assets.setTotalIncome(totalIncome.getTotalIncome());
                assets.setTotalAmount(totalIncome.getTotalAmount());
                assets.setIncomeFromPoints(totalIncome.getIncomeFromPoints());
                assets.setPlatformServiceFee(totalIncome.getPlatformServiceFee());
                assets.setOrderCreationTime(totalIncome.getOrderCreationTime());
                //微信支付合计
                SlMerchantAssets wechatTotalAmount = slOrderMapper.wechatTotalAmount(slbShop.getId(), createTime);
                assets.setWechatRevenue(wechatTotalAmount.getWechatRevenue());
                //支付宝支付合计
                SlMerchantAssets alipayRevenue = slOrderMapper.alipayRevenue(slbShop.getId(), createTime);
                assets.setAlipayRevenue(alipayRevenue.getAlipayRevenue());
                log.info("执行结算单店铺为{}", slbShop);
                count+=1;
                this.statisticalBalance(assets, slbShop, createTime,2);
            }
            log.info("执行了{}条数据",count);
            //查询当日下单涉及店铺
            List<Map<String, Object>> getPlaceOrderShop = slOrderMapper.getPlaceOrderShop(createTime);
            for (Map shopId : getPlaceOrderShop) {
                SlbShop selectById = slShopMapper.selectById(Convert.toInt(shopId.get("shopId")));
                if (ObjectUtils.isEmpty(selectById)) {
                    log.info("该店铺信息异常，ID为{}", Convert.toInt(shopId.get("shopId")));
                    break;
                }
                SlMerchantAssets assets = new SlMerchantAssets();
                assets.setShopId(selectById.getId());
                assets.setShopName(selectById.getName());
                assets.setSlShopType(selectById.getSlShopType());
                assets.setUserId(selectById.getOwnerId());
                assets.setType(1);
                //查询订单交易金额、积分收入总额,手续费
                SlMerchantAssets totalOrderAmount = slOrderMapper.totalOrderAmount(selectById.getId(), createTime);
                assets.setTotalAmount(totalOrderAmount.getTotalAmount());
                assets.setPlatformServiceFee(totalOrderAmount.getPlatformServiceFee());
                assets.setOrderCreationTime(totalOrderAmount.getOrderCreationTime());
                log.info("执行用户下单店铺为{}", selectById);
                this.statisticalBalance(assets, selectById, createTime,1);
            }
            log.info("搜了宝商家资产汇总定时任务执行完成!");
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
            message.setSuccess(true);
        } catch (Exception e) {
            log.error("搜了宝商家资产汇总定时任务执行失败,原因{}", e.getMessage());
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            message.setSuccess(false);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return message;
    }

    @Transactional(rollbackFor = Exception.class)
    @DataSource(name = "jyb_soole_data_hn")
    public void statisticalBalance(SlMerchantAssets assets, SlbShop slbShop, String createTime, Integer type) {
        //今日店铺余额
        SlMerchantAssets todayStoreBalance = slShopWalletMapper.todayStoreBalance(slbShop.getOwnerId());
        if (ObjectUtils.isEmpty(todayStoreBalance)){
            assets.setTodayStoreBalance(new BigDecimal(0));
        }else {
            assets.setTodayStoreBalance(todayStoreBalance.getTodayStoreBalance());
        }
        QueryWrapper<SlShopWallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", slbShop.getOwnerId());
        queryWrapper.eq("type", 0);
        SlShopWallet slShopWallet = slShopWalletMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(slShopWallet)){
            //店铺可提现余额
            assets.setWithdrawalAmount(new BigDecimal(0));
            //店铺冻结余额
            assets.setFrozenAmount(new BigDecimal(0));
        }else {
            //店铺可提现余额
            assets.setWithdrawalAmount(slShopWallet.getAvailableBalance());
            //店铺冻结余额
            assets.setFrozenAmount(slShopWallet.getGwjBalance());
        }
        SlMerchantAssets todayExpenditureAmount = slShopWalletMapper.todayExpenditureAmount(slbShop.getOwnerId(), createTime);
        assets.setTodayExpenditureAmount(todayExpenditureAmount.getTodayExpenditureAmount());
        //昨日记录
        SlMerchantAssets yesterday = slMerchantAssetsMapper.yesterday(slbShop.getId(), createTime,type);
        if (ObjectUtils.isEmpty(yesterday)) {
            assets.setYesterdayStoreBalance(assets.getTodayStoreBalance());
            assets.setYesterdayExpenditureAmount(new BigDecimal(0));
        } else {
            assets.setYesterdayStoreBalance(yesterday.getTodayStoreBalance());
            assets.setYesterdayExpenditureAmount(yesterday.getTodayExpenditureAmount());
        }
        slMerchantAssetsMapper.insert(assets);
    }


    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage pageMerchantAssets(PageMerchantAssetsParam param) {
        BusinessMessage message = new BusinessMessage();
        PageMerchantAssetsRsp assetsRsp = new PageMerchantAssetsRsp();
        QueryWrapper<SlMerchantAssets> queryWrapper = this.assetsQueryWrapper(param);
        Page<SlMerchantAssets> assetsPage = slMerchantAssetsMapper.selectPage(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        assetsRsp.setAssetsPage(assetsPage);
        //商家数量
        PageMerchantAssetsRsp shxopCount = slMerchantAssetsMapper.selectshxopCount(param);
        assetsRsp.setShopCount(shxopCount.getShopCount());
        //金额合计
        PageMerchantAssetsRsp sumAmount = slMerchantAssetsMapper.sumAmount(param);
        assetsRsp.setSumTotalIncome(sumAmount.getSumTotalIncome());
        assetsRsp.setSumWechatRevenue(sumAmount.getSumWechatRevenue());
        assetsRsp.setSumAlipayRevenue(sumAmount.getSumAlipayRevenue());
        assetsRsp.setSumIncomeFromPoints(sumAmount.getSumIncomeFromPoints());
        assetsRsp.setSumPlatformServiceFee(sumAmount.getSumPlatformServiceFee());
       Map<String,Object> sumTotalAmount=slMerchantAssetsMapper.sumTotalAmount(param);
       assetsRsp.setSumTotalAmount(Convert.toBigDecimal(sumTotalAmount.get("sumTotalAmount")));
        Map<String,Object> sumUnsettled=slMerchantAssetsMapper.sumUnsettled(param);
        assetsRsp.setSumUnsettled(Convert.toBigDecimal(sumUnsettled.get("sumUnsettled")));
        message.setData(assetsRsp);
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.failCode);
        return message;
    }

    public QueryWrapper<SlMerchantAssets> assetsQueryWrapper(PageMerchantAssetsParam param) {
        QueryWrapper<SlMerchantAssets> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 2);
        if (ObjectUtils.isNotEmpty(param.getUserId())) {
            queryWrapper.eq("user_id", param.getUserId());
        }
        if (ObjectUtils.isNotEmpty(param.getShopName())) {
            queryWrapper.like("shop_name", param.getShopName());
        }
        if (ObjectUtils.isNotEmpty(param.getSlShopType())) {
            queryWrapper.eq("sl_shop_type", param.getSlShopType());
        }
        if (ObjectUtils.isNotEmpty(param.getCreatedBeginTime()) && ObjectUtils.isNotEmpty(param.getCreatedEndTime())) {
            queryWrapper.ge("order_creation_time", param.getCreatedBeginTime());
            queryWrapper.le("order_creation_time", param.getCreatedEndTime());
        }
        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public void merchantAssetsExcel(HttpServletResponse response, PageMerchantAssetsParam param) {
        String assetsId = param.getAssetsId();
        if (ObjectUtils.isNotEmpty(assetsId)) {
            String[] split = assetsId.split(",");
            param.setSplit(split);
        }
        PageMerchantAssetsRsp shxopCount = slMerchantAssetsMapper.selectshxopCount(param);
        PageMerchantAssetsRsp sumAmount = slMerchantAssetsMapper.sumAmount(param);
        List<SlMerchantAssets> slMerchantAssets = slMerchantAssetsMapper.merchantAssetsExcel(param);
        Map<String,Object> sumTotalAmount=slMerchantAssetsMapper.sumTotalAmount(param);
        Map<String,Object> sumUnsettled=slMerchantAssetsMapper.sumUnsettled(param);
        try {
            List<List<Object>> rows = new ArrayList();
            ExcelData data = new ExcelData();
            data.setName("商家资产导出");//sheet表名称
            List<String> sumTitles = new ArrayList();
            sumTitles.add("商家数量");
            sumTitles.add(Convert.toStr(shxopCount.getShopCount()));
            sumTitles.add("订单交易金额汇总");
            sumTitles.add(Convert.toStr(sumTotalAmount.get("sumTotalAmount")));
            sumTitles.add("订单未结算金额汇总");
            sumTitles.add(Convert.toStr(sumUnsettled.get("sumUnsettled")));
            sumTitles.add("积分收入汇总");
            sumTitles.add(Convert.toStr(sumAmount.getSumIncomeFromPoints()));
            sumTitles.add("微信收入汇总");
            sumTitles.add(Convert.toStr(sumAmount.getSumWechatRevenue()));
            sumTitles.add("支付宝收入汇总");
            sumTitles.add(Convert.toStr(sumAmount.getSumAlipayRevenue()));
            sumTitles.add("今日合计收入金额汇总");
            sumTitles.add(Convert.toStr(sumAmount.getSumTotalIncome()));
            sumTitles.add("平台服务费收入汇总");
            sumTitles.add(Convert.toStr(sumAmount.getSumPlatformServiceFee()));
            data.setTitles(sumTitles);
            //表头
            List<Object> titles = new ArrayList();
            titles.add("商家用户ID");
            titles.add("店铺名称");
            titles.add("商家类型");
            titles.add("订单交易金额");
            titles.add("积分收入");
            titles.add("微信收入");
            titles.add("支付宝收入");
            titles.add("今日合计收入金额");
            titles.add("店铺今日余额");
            titles.add("店铺冻结余额");
            titles.add("店铺可提现余额");
            titles.add("店铺支出金额");
            titles.add("店铺昨日余额");
            titles.add("店铺昨日支出金额");
            titles.add("平台服务费(7%)");
//            data.setTitles(titles);
            rows.add(titles);
            for (SlMerchantAssets assets : slMerchantAssets) {
                List<Object> row1 = new ArrayList();
                row1.add(assets.getUserId());
                row1.add(assets.getShopName());
                if (ObjectUtils.isNotEmpty(assets.getSlShopType())) {
                    if (assets.getSlShopType().equals(0)) {
                        row1.add("普通店铺");
                    } else if (assets.getSlShopType().equals(1)) {
                        row1.add("普通加盟店铺");
                    } else if (assets.getSlShopType().equals(2)) {
                        row1.add("运营中心店铺");
                    } else if (assets.getSlShopType().equals(3)) {
                        row1.add("厂家店铺");
                    }
                }
                row1.add(assets.getTotalAmount());
                row1.add(assets.getIncomeFromPoints());
                row1.add(assets.getWechatRevenue());
                row1.add(assets.getAlipayRevenue());
                row1.add(assets.getTotalIncome());
                row1.add(assets.getTodayStoreBalance());
                row1.add(assets.getFrozenAmount());
                row1.add(assets.getWithdrawalAmount());
                row1.add(assets.getTodayExpenditureAmount());
                row1.add(assets.getYesterdayStoreBalance());
                row1.add(assets.getYesterdayExpenditureAmount());
                row1.add(assets.getPlatformServiceFee());
                rows.add(row1);
            }
            data.setRows(rows);
            ExportExcelUtils.exportExcel(response, "商家资产记录导出.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
